package com.walnut.servlet;

import com.walnut.dao.FoodDao;
import com.walnut.dao.impl.FoodDaoImpl;
import com.walnut.pojo.Food;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/addFood")
@MultipartConfig
public class AddFoodServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        ServletContext context = getServletContext();
        request.setCharacterEncoding("UTF-8");

        try {
            Food food = new Food().builder()
                .foodName(request.getParameter("foodName"))
                .price(Double.parseDouble(request.getParameter("price")))
                .foodImg(request.getParameter("foodImgUrl"))
                .foodStatus(request.getParameter("foodStatus"))
                .build();
            FoodDao foodDao = new FoodDaoImpl();

            if (foodDao.selectByName(food.getFoodName())==1) {
                context.setAttribute("message", "添加失败，该食品已存在");
                request.getRequestDispatcher("/foodList").forward(request, response);
            }
            else {
                int count=foodDao.insert(food);
                if (count==1){
                    context.setAttribute("message", "添加成功");
                }else {
                    context.setAttribute("message", "添加失败,服务器内部错误");
                }
                request.getRequestDispatcher("/foodList").forward(request, response);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}